package com.nowcoder.community.controller;

import com.nowcoder.community.event.EventProducer;
import com.nowcoder.community.pojo.Event;
import com.nowcoder.community.pojo.Page;
import com.nowcoder.community.pojo.User;
import com.nowcoder.community.service.FollowService;
import com.nowcoder.community.service.UserService;
import com.nowcoder.community.util.CommunityConstant;
import com.nowcoder.community.util.CommunityUtil;
import com.nowcoder.community.util.HostHolder;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.Map;

@Api(description = "关注相关")
@Controller
public class FollowController implements CommunityConstant{

    @Autowired
    @Qualifier("followService")
    private FollowService followService;

    @Autowired
    @Qualifier("userService")
    private UserService userService;

    @Autowired
    private EventProducer producer;

    @Autowired
    private HostHolder hostHolder;

    @ApiOperation(value = "关注用户接口")
    @PostMapping("/follow")
    @ResponseBody
    @ApiImplicitParams({
        @ApiImplicitParam(name = "entityType", value = "实体类型"),
        @ApiImplicitParam(name = "entityId", value = "实体id")
    })
    public String follow(int entityType, int entityId){
        User user = hostHolder.getUser();

        //关注
        followService.follow(user.getId(), entityType, entityId);

        //上面的操作完成后，触发关注事件
        Event event = new Event()
                .setTopic(TOPIC_FOLLOW)
                .setUserId(hostHolder.getUser().getId())
                .setEntityType(entityType)
                .setEntityId(entityId)
                .setEntityUserId(entityId);
        producer.fireEvent(event);

        return CommunityUtil.getJSONString(0, "已关注！");
    }

    @ApiOperation(value = "取消关注接口")
    @PostMapping("/unFollow")
    @ResponseBody
    @ApiImplicitParams({
        @ApiImplicitParam(name = "entityType", value = "实体类型"),
        @ApiImplicitParam(name = "entityId", value = "实体id")
    })
    public String unFollow(int entityType, int entityId){
        User user = hostHolder.getUser();

        //取消关注
        followService.unFollow(user.getId(), entityType, entityId);

        return CommunityUtil.getJSONString(0, "已取消关注！");
    }

    @ApiOperation(value = "获取关注我的用户列表接口")
    @GetMapping("/followees/{userId}")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "userId", value = "用户id"),
        @ApiImplicitParam(name = "page", value = "分页实例")
    })
    public String getFollowees(@PathVariable("userId") int userId, Page page, Model model){

        User user = userService.findUserById(userId);

        if (user == null){
            throw new RuntimeException("用户不存在！");
        }

        model.addAttribute("user", user);

        page.setLimit(5);
        page.setPath("/followees/" + userId);
        page.setRows((int)followService.findFolloweeCount(userId, ENTITY_TYPE_USER));

        List<Map<String ,Object>> userList = followService.findFollowees(userId, page.getOffset(), page.getLimit());
        if (userList != null){
            for (Map<String, Object> map : userList) {
                User u = (User)map.get("user");
                //保存当前用户是否关注了某个用户的判断值
                map.put("hasFollowed", hasFollowed(u.getId()));
            }
        }
        model.addAttribute("users", userList);

        return "site/followee";
    }

    @ApiOperation(value = "获取我关注的用户的用户列表接口")
    @GetMapping("/followers/{userId}")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "userId", value = "用户id"),
        @ApiImplicitParam(name = "page", value = "分页实例")
    })
    public String getFollowers(@PathVariable("userId") int userId, Page page, Model model){

        User user = userService.findUserById(userId);

        if (user == null){
            throw new RuntimeException("用户不存在！");
        }

        model.addAttribute("user", user);

        page.setLimit(5);
        page.setPath("/followers/" + userId);
        page.setRows((int)followService.findFollowerCount(ENTITY_TYPE_USER, userId));

        List<Map<String ,Object>> userList = followService.findFollowers(userId, page.getOffset(), page.getLimit());
        if (userList != null){
            for (Map<String, Object> map : userList) {
                User u = (User)map.get("user");
                //保存当前用户是否关注了某个用户的判断值
                map.put("hasFollowed", hasFollowed(u.getId()));
            }
        }
        model.addAttribute("users", userList);

        return "site/follower";
    }

    //查询当前用户是否关注了某个用户
    private boolean hasFollowed(int userId){
        if (hostHolder.getUser() == null){
            return false;
        }

        return followService.hasFollowed(hostHolder.getUser().getId(), ENTITY_TYPE_USER, userId);
    }

}
